package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishMapper;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 衷岚
 * @version 1.0
 */
@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealMapper setmealMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addWithFlavor(DishDTO dishDTO) {

        //插入菜品表数据
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.add(dish);

        //主键回显
        Long dishId = dish.getId();

        //插入菜品口味表数据
        //因为口味是可以不传来数据的 这里做是否有数据判断
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            flavors.forEach(flavor -> {
                flavor.setDishId(dishId);
            });
            dishFlavorMapper.add(flavors);

        }



    }

    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {

        Dish dish = new Dish();
        BeanUtils.copyProperties(dishPageQueryDTO, dish);
        //分页插件
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());

        List<DishVO> dishVOList = dishMapper.pageQuery(dish);
        Page page = (Page) dishVOList;

        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public void updateStatus(Integer status, Long id) {
        Dish dish = new Dish();
        dish.setId(id);
        //TODO 完成 菜品状态为禁用，菜品关联的套餐也禁用业务
        //如果菜品状态为禁用，菜品关联的套餐也禁用
//        if(status==StatusConstant.DISABLE){
//            //查询所有关联套餐ids
//            //批量禁用套餐
//
//        }
        dish.setStatus(status);
        dishMapper.update(dish);
    }

    @Override
    public List<Dish> findByCategoryId(Long categoryId) {
        List<Dish> dishList = dishMapper.findByCategoryId(categoryId);
        return dishList;
    }

    @Override
    public DishVO findWithFlavorById(Long id) {
        //查找菜品信息，关联的口味信息
        Dish dish = dishMapper.findById(id);
        List<DishFlavor> dishFlavorList = dishFlavorMapper.findByDishId(id);
        //封装返回
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(dishFlavorList);
        return dishVO;
    }


    /**
     * 批量删除（全删或一个都不删），ids里有一个不能删除其他都不能删除
     * @param ids 菜品id列表
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<Long> ids) {
        //菜品是起售状态不能删除
        for (Long id :ids) {
            Dish dish = dishMapper.findById(id);
            if(dish.getStatus() == StatusConstant.ENABLE){
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        //套餐内关联的菜品不能删除
        List<SetmealDish> setmealDishList = setmealDishMapper.findByDishIds(ids);
        if(setmealDishList!=null && setmealDishList.size()>0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        //批量菜品删除后，对应的口味也都删除
        dishMapper.deleteByIds(ids);
        dishFlavorMapper.deleteByDishIds(ids);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(DishDTO dishDTO) {
        //封装到实体类中
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        //口味信息
        List<DishFlavor> flavorList = dishDTO.getFlavors();

        //修改菜品信息
        dishMapper.update(dish);

        //删除之前关联的口味信息
        dishFlavorMapper.deleteByDishId(dish.getId());

        //插入新的口味信息
        flavorList.forEach(flavor -> {
            flavor.setDishId(dish.getId());
        });
        if(flavorList!=null && flavorList.size()>0){
            dishFlavorMapper.add(flavorList);
        }
    }

    @Override
    public List<DishVO> findWithFlavorByCategoryId(Long categoryId) {
        //创建dishvo集合
        List<DishVO> dishVOList = new ArrayList<DishVO>();

        //根据分类id查询所有菜品
        List<Dish> dishList = dishMapper.findByCategoryId(categoryId);
        //菜品循环
        // 查询每个菜品和对应关联的所有口味
        for (Dish dish : dishList) {
            DishVO dishVO = findWithFlavorById(dish.getId());
            //加入dishVO集合中
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
